package pri.zjy.matrix;

import java.util.Arrays;

/**
 * @author zhangjy
 * @description LCR 146. 螺旋遍历二维数组
 * @date 2025/3/28 11:06
 */
public class SpiralArray_146 {

    public static void main(String[] args) {
        SpiralArray_146 spiralArray146 = new SpiralArray_146();
        int[][] array = {{1, 2, 3}, {8, 9, 4}, {7, 6, 5}};
        Arrays.stream(spiralArray146.spiralArray(array)).forEach(System.out::println);

    }

    // TODO 当前解法错误
    public int[] spiralArray(int[][] array) {
        int rows = array.length, cols = array[0].length;
        // 二维数组待螺旋遍历次数（数组层数）
        int layer = Math.min(rows, cols) - 1;
        boolean right = true, down = false, left = false, up = false;
        int[] res = new int[rows + cols];
        int index = 0, currentLayer = 1, count = 0;
        while (currentLayer < layer) {
            while (count < 4) {
                if (right) {
                    // 右（列动，行不变）
                    for (int i = currentLayer - 1; i < cols - currentLayer; i++) {
                        res[index] = array[currentLayer - 1][i];
                        index++;
                    }
                    right = false;
                    down = true;
                    count++;
                } else if (down) {
                    // 下（行动，列不变）
                    for (int i = currentLayer - 1; i < rows - currentLayer; i++) {
                        res[index] = array[i][currentLayer - 1];
                        index++;
                    }
                    down = false;
                    left = true;
                    count++;
                } else if (left) {
                    // 左（列动，行不变）
                    for (int i = currentLayer - 1; i < cols - currentLayer; i++) {
                        res[index] = array[currentLayer - 1][i];
                        index++;
                    }
                    left = false;
                    up = true;
                    count++;
                } else if (up) {
                    // 上（行动，列不变）
                    for (int i = currentLayer - 1; i < rows - currentLayer; i++) {
                        res[index] = array[i][currentLayer - 1];
                        index++;
                    }
                    up = false;
                    right = true;
                    count++;
                }
            }
            currentLayer++;
        }

        return res;
    }

}
